package com.ssd.redis;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Redis自动配置类，用于配置RedisTemplate和CacheManager
 */
@Configuration
public class RedisAutoConfiguration {
    // Jackson ObjectMapper用于JSON序列化和反序列化
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static{
        // 配置ObjectMapper以支持LocalDate和LocalDateTime的序列化和反序列化
        JavaTimeModule timeModule = new JavaTimeModule();
        timeModule.addDeserializer(LocalDate.class,
                new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        timeModule.addDeserializer(LocalDateTime.class,
                new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        timeModule.addSerializer(LocalDate.class,
                new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        timeModule.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        OBJECT_MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        OBJECT_MAPPER.registerModule(timeModule);
    }

    /**
     * 创建RedisTemplate模板类配置
     * @param redisConnnectionFactory Redis连接工厂
     * @return 配置好的RedisTemplate对象
     */
    @Bean("redisTemplate")
    @Primary
    public RedisTemplate<String, Object> restTemplate(RedisConnectionFactory redisConnnectionFactory) {
        //支持别名映射，即使类路径修改了
//        ObjectMapper mapper = new ObjectMapper();
//        mapper.registerModule(new SimpleModule()
//                .registerSubtypes(new NamedType(LoginUser.class, "loginUser")));
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnnectionFactory);
        // 设置键值的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置值的序列化方式
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        // 设置Hash类型键值的序列化方式
        redisTemplate.setHashKeySerializer(new GenericToStringSerializer(String.class));
        // 设置Hash类型值的序列化方式
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer(OBJECT_MAPPER));
        return redisTemplate;
    }

//    /**
//     * 创建并配置RedisTemplate实例
//     *
//     * @param redisConnectionFactory Redis连接工厂，用于建立Redis连接
//     * @return 配置好的RedisTemplate实例，用于操作Redis
//     */
//    @Bean(name = "redisTemplate")
//    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
////        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
////
////        redisTemplate.setConnectionFactory(redisConnectionFactory);
////        redisTemplate.setKeySerializer(keySerializer());
////        redisTemplate.setHashKeySerializer(keySerializer());
////        redisTemplate.setValueSerializer(valueSerializer());
////        redisTemplate.setHashValueSerializer(valueSerializer());
////
////        return redisTemplate;
//        RedisTemplate<Object, Object> template = new RedisTemplate<>();
//        template.setConnectionFactory(redisConnectionFactory);
//
//        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
//
//        // 使用StringRedisSerializer来序列化和反序列化redis的key值
//        template.setKeySerializer(new StringRedisSerializer());
//        template.setValueSerializer(serializer);
//
//
//        // Hash的key也采用StringRedisSerializer的序列化方式
////        template.setHashKeySerializer(new StringRedisSerializer());
////        template.setHashValueSerializer(serializer);
//        template.setHashKeySerializer(keySerializer());
//        template.setHashValueSerializer(valueSerializer());
//
//        template.afterPropertiesSet();
//        return template;
//    }

    /**
     * 创建并配置CacheManager实例，用于管理缓存
     *
     * @param redisConnectionFactory Redis连接工厂，用于建立Redis连接
     * @return 配置好的CacheManager实例，用于缓存管理
     */
    @Primary
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
        //缓存配置对象
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();

        redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) //设置缓存的默认超时时间：30分钟
                .disableCachingNullValues()             //如果是空值，不缓存
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))         //设置key序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer())));  //设置value序列化器

        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }

    /**
     * 创建并配置Key序列化器
     *
     * @return 配置好的StringRedisSerializer实例，用于序列化Key
     */
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }

    /**
     * 创建并配置Value序列化器
     *
     * @return 配置好的Jackson2JsonRedisSerializer实例，用于序列化Value
     */
    private RedisSerializer<Object> valueSerializer() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        return jackson2JsonRedisSerializer;
    }
}

